package com.atguigui.leetcode;

/**
 * 468.验证IP地址
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by  wangjiaxin  on 2022/5/29 21:04
 */
public class P468ValidateIpAddress {
    public static void main(String[] args) {
        Solution solution = new P468ValidateIpAddress().new Solution();
        String ipAddress = solution.validIPAddress("172.16.254.1");

        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public String validIPAddress(String queryIP) {

            String word = "0123456789abcdefABCDEF";

            String[] split1 = queryIP.split(".");
            String[] split2 = queryIP.split(":");

            // 排除结尾为 . 或 : 切分不到的情况
            if (queryIP.endsWith("\\.") || queryIP.endsWith("\\:")) {
                return "Neither";
            }

            // 判断是否为 IPv4
            if (split1.length == 4) {
                for (String str : split1) {
                    try {
                        Integer integer = new Integer(str);
                        if (integer < 0 || integer > 255) {
                            return "Neither";
                        }
                        // 判断是否为 前导零
                        if (str.length() != (integer + "").length()) {
                            return "Neither";
                        }
                    } catch (Exception e) {
                        return "Neither";
                    }
                }
                return "IPv4";
            } else if (split2.length == 8) {    // 判断是否为 IPv6

                for (String str : split2) {
                    if (str.length() < 1 || str.length() > 4) {
                        return "Neither";
                    }
                    for (int i = 0; i < str.length(); i++) {
                        String s = str.substring(i, i + 1);
                        // 是否是在16进制字符内
                        if (!word.contains(s)) {
                            return "Neither";
                        }
                    }
                }
                return "IPv6";
            }

            return "Neither";
        }
    }
}
